package com.zige.zige.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zige.zige.LittleZebraApplication;
import com.zige.zige.R;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.CheckUtils;
import com.zige.zige.utils.NetworkUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;
import com.zige.zige.view.TimerButton;

import org.json.JSONObject;

import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Fei on 2016/3/7.
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private Button btn_login;
    private View view_zhuce, view_login;
    private LinearLayout lay_login, lay_getcode, lay_register, lay_next, lay_back, lay_body;
    /**
     * 注册
     */
    private Button btn_zhu, btn_register_getCode, btn_register_ok, btn_timer_getCode;
    private EditText ed_register_username, ed_register_password, ed_register_code;
    private ImageView img_register_clear, img_code_refresh;
    private TextView tv_useragreement, tv_forgetPassword;
    private CheckBox user_checkbox;

    private boolean isCheck = true;

    private int textWhite;
    private int textBlue;
    private int lineBlue;
    private int lineWhite;


    /**
     * 登录
     */
    private EditText ed_login_username, ed_login_password;
    private Button btn_userLogin;
    private ImageView img_login_clear;

    private Activity activity;
    private String dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        activity = this;
        dialog = getIntent().getStringExtra("dialog");
        initColor();
        initView();
    }

    private void initColor() {
        textWhite = getResources().getColor(R.color.m_btn_text);
        textBlue = getResources().getColor(R.color.m_view_bg_select);//m_view_bg_select
        lineWhite = getResources().getColor(R.color.white);
        lineBlue = getResources().getColor(R.color.m_view_bg_select);
    }

    private void initView() {
        lay_back = serchViewById(R.id.lay_back);
        lay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back2Main();
                finish();
            }
        });
        view_zhuce = serchViewById(R.id.view_zhuce);
        view_login = serchViewById(R.id.view_login);

        btn_zhu = serchViewById(R.id.zhuce_btn);
        btn_zhu.setOnClickListener(new ColoerButtonListener());
        btn_login = serchViewById(R.id.login_btn);
        btn_login.setOnClickListener(new ColoerButtonListener());

        lay_login = serchViewById(R.id.lay_login);
        lay_register = serchViewById(R.id.lay_register);
        lay_getcode = serchViewById(R.id.lay_getcode);
        lay_next = serchViewById(R.id.lay_next);



        /**注册*/
        lay_body = serchViewById(R.id.lay_body);
        btn_register_getCode = serchViewById(R.id.btn_register_getCode);
        btn_register_getCode.setOnClickListener(this);
        btn_register_ok = serchViewById(R.id.btn_register_ok);
        btn_register_ok.setOnClickListener(this);
        lay_getcode = serchViewById(R.id.lay_getcode);
        btn_timer_getCode = serchViewById(R.id.btn_timer_getCode);
        btn_timer_getCode.setOnClickListener(this);
        img_code_refresh = serchViewById(R.id.img_code_refresh);
        img_code_refresh.setOnClickListener(this);
        ed_register_username = serchViewById(R.id.ed_register_username);
        ed_register_password = serchViewById(R.id.ed_register_password);
        ed_register_code = serchViewById(R.id.ed_register_code);
        img_register_clear = serchViewById(R.id.img_register_clear);
        img_register_clear.setOnClickListener(this);
        tv_useragreement = serchViewById(R.id.tv_useragreement);
        tv_useragreement.setOnClickListener(this);
        user_checkbox = serchViewById(R.id.user_checkbox);
        user_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCheck = isChecked;
            }
        });
        /**登录*/
        ed_login_username = serchViewById(R.id.ed_login_username);
        img_login_clear = serchViewById(R.id.img_login_clear);
        img_login_clear.setOnClickListener(this);
        ed_login_password = serchViewById(R.id.ed_login_password);
        btn_userLogin = serchViewById(R.id.btn_userLogin);
        btn_userLogin.setOnClickListener(this);
        tv_forgetPassword = serchViewById(R.id.tv_forgetPassword);
        tv_forgetPassword.setOnClickListener(this);

        UserInfo userInfo = LittleZebraApplication.getInstance().getRegisterUser();
        if (userInfo != null) {
            if (!TextUtils.isEmpty(userInfo.phoneNumber)) {
                ed_login_username.setText(userInfo.phoneNumber);
            }

            if (!TextUtils.isEmpty(userInfo.userPassword)) {
                ed_login_password.setText(userInfo.userPassword);
            }
        }


        if(!TextUtils.isEmpty(dialog)){
            changeColor(textBlue, textWhite, lineBlue, lineWhite);
            lay_login.setVisibility(View.GONE);
            lay_register.setVisibility(View.VISIBLE);
            lay_body.setVisibility(View.VISIBLE);
        }


    }

    class ColoerButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {


            switch (v.getId()) {
                case R.id.zhuce_btn:
                    changeColor(textBlue, textWhite, lineBlue, lineWhite);
                    lay_login.setVisibility(View.GONE);
                    lay_register.setVisibility(View.VISIBLE);
                    lay_body.setVisibility(View.VISIBLE);
//                    Animation animation = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.view_right_in);
//                    view_zhuce.startAnimation(animation);
                    break;
                case R.id.login_btn:
                    changeColor(textWhite, textBlue, lineWhite, lineBlue);
                    lay_login.setVisibility(View.VISIBLE);
                    lay_register.setVisibility(View.GONE);
//                    Animation animation2 = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.view_left_in);
//                    view_zhuce.startAnimation(animation2);
                    break;
            }
        }
    }

    private void changeColor(int text1, int text2, int line1, int line2) {
        btn_zhu.setTextColor(text1);
        btn_login.setTextColor(text2);

        view_zhuce.setBackgroundColor(line1);
        view_login.setBackgroundColor(line2);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register_getCode:
                if (TextUtils.isEmpty(ed_register_username.getText().toString())) {
                    showErrorDialog("手机号码不能为空");
                    return;
                }
                if (!CheckUtils.isMobile(ed_register_username.getText().toString())) {
                    showErrorDialog("您输入的手机号码有误");
                    return;
                }
                if (ed_register_username.getText().toString().length() != 11) {
                    showErrorDialog("您输入手机号码不正确");
                    return;
                }
                if (TextUtils.isEmpty(ed_register_password.getText().toString())) {
                    showErrorDialog("登录密码不能为空");
                    return;
                }
                if (ed_register_password.getText().toString().length() < 6) {
                    showErrorDialog("密码最少为6位");
                    return;
                }

                getCode();
                break;
            case R.id.tv_forgetPassword:
                startActivity(new Intent(RegisterActivity.this, RetrievePasswordActivity.class));
                break;
            case R.id.btn_timer_getCode:
                if (TextUtils.isEmpty(ed_register_username.getText().toString())) {
                    showErrorDialog("手机号码不能为空");
                    return;
                }
                if (!CheckUtils.isMobile(ed_register_username.getText().toString())) {
                    showErrorDialog("您输入的手机号码有误");
                    return;
                }
                if (ed_register_username.getText().toString().length() != 11) {
                    showErrorDialog("您输入手机号码不正确");
                    return;
                }
                if (TextUtils.isEmpty(ed_register_password.getText().toString())) {
                    showErrorDialog("登录密码不能为空");
                    return;
                }
                if (ed_register_password.getText().toString().length() < 6) {
                    showErrorDialog("密码最少为6位");
                    return;
                }
                getCode();
                break;
            case R.id.img_code_refresh:
                if (TextUtils.isEmpty(ed_register_username.getText().toString())) {
                    showErrorDialog("手机号码不能为空");
                    return;
                }
                if (!CheckUtils.isMobile(ed_register_username.getText().toString())) {
                    showErrorDialog("您输入的手机号码有误");
                    return;
                }
                if (ed_register_username.getText().toString().length() != 11) {
                    showErrorDialog("您输入手机号码不正确");
                    return;
                }
                if (TextUtils.isEmpty(ed_register_password.getText().toString())) {
                    showErrorDialog("登录密码不能为空");
                    return;
                }
                if (ed_register_password.getText().toString().length() < 6) {
                    showErrorDialog("密码最少为6位");
                    return;
                }
                getCode();
                break;
            case R.id.tv_useragreement:
                startActivity(new Intent(activity, UserAgreementActivity.class));
                break;
            case R.id.btn_register_ok:
                if (TextUtils.isEmpty(ed_register_username.getText().toString())) {
                    showErrorDialog("手机号码不能为空");
                    return;
                }
                if (!CheckUtils.isMobile(ed_register_username.getText().toString())) {
                    showErrorDialog("您输入的手机号码有误");
                    return;
                }
                if (ed_register_username.getText().toString().length() != 11) {
                    showErrorDialog("您输入手机号码不正确");
                    return;
                }
                if (TextUtils.isEmpty(ed_register_password.getText().toString())) {
                    showErrorDialog("登录密码不能为空");
                    return;
                }
                if (ed_register_password.getText().toString().length() < 6) {
                    showErrorDialog("密码最少为6位");
                    return;
                }
                if (TextUtils.isEmpty(ed_register_code.getText().toString())) {
                    showErrorDialog("验证码不能为空");
                    return;
                }
                if (isCheck == false) {
                    showErrorDialog("您还没有同意小伴马协议");
                    return;
                }
                setRegistered();
                break;
            case R.id.img_register_clear:
                ed_register_username.setText("");
                break;
            case R.id.img_login_clear:
                ed_login_username.setText("");
                break;
            case R.id.btn_userLogin:
                if (TextUtils.isEmpty(ed_login_username.getText().toString())) {
                    showErrorDialog("手机号码不能为空");
                    return;
                }
                if (!CheckUtils.isMobile(ed_login_username.getText().toString())) {
                    showErrorDialog("您输入的手机号码有误");
                    return;
                }

                if (TextUtils.isEmpty(ed_login_password.getText().toString())) {
                    showErrorDialog("登录密码不能为空");
                    return;
                }
                if (ed_login_password.getText().toString().length() < 6) {
                    showErrorDialog("密码最少为6位");
                    return;
                }
                if (NetworkUtils.isNetworkAvailable(activity)) {
                    userLogin();
                } else {
                    showErrorDialog("网络异常");

                }
                break;
        }
    }

    private String codeType = "0";//0表示 注册 验证码

    private void getCode() {
        String phoneNumber = ed_register_username.getText().toString();
        HashMap<String, String> parms = new HashMap<>();
        parms.put("phone", phoneNumber);
        parms.put("type", codeType);
        parms.put("deviceId",SystemUtils.getDeviceKey(this));
        showLoadingDialog();
        TaskExecutor.getInstance().execute(
                new PostRequestTask(parms, activity, UrlConsts.GET_CODE) {
                    @Override
                    protected void handleResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            int code = object.getInt("code");
                            String msg = object.getString("message");
                            if (code == 0000) {
                                lay_getcode.setVisibility(View.VISIBLE);
                                btn_register_getCode.setVisibility(View.GONE);
                                lay_next.setVisibility(View.VISIBLE);
                                closeLoadingDialog();
                                showErrorDialog("验证码已发送到您的手机");
                                TimerButton timerButton = new TimerButton(RegisterActivity.this, 30000, 1000, btn_timer_getCode, img_code_refresh);
                                timerButton.start();
                            } else {
                                throw new Exception(msg);
                            }
                        } catch (Exception e) {
                            ToastUtils.showToast(activity, e.getMessage());
                            ed_login_username.setText(ed_register_username.getText().toString());
                            ed_login_password.setText(ed_register_password.getText().toString());
                        } finally {
                            closeLoadingDialog();
                        }
                    }
                }

        );
    }


    private void setRegistered() {
        HashMap<String, String> params = new HashMap<>();
        params.put("phone", ed_register_username.getText().toString());
        params.put("password", ed_register_password.getText().toString());
        params.put("verifyCode", ed_register_code.getText().toString());
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(
                                                   params, activity, UrlConsts.USER_REGISTERED) {
                                               @Override
                                               protected void handleResponse(String response) {
                                                   try {
                                                       JSONObject object = new JSONObject(response);
                                                       int code = object.getInt("code");
                                                       String msg = object.getString("message");
                                                       String userId = object.getString("uid");
                                                       if (code == 0000) {
                                                           closeLoadingDialog();

                                                           UserInfo userInfo = new UserInfo();
                                                           userInfo.phoneNumber = ed_register_username.getText().toString();
                                                           userInfo.userPassword = ed_register_password.getText().toString();
                                                           LittleZebraApplication.getInstance().setRegitserUser(userInfo);

                                                           ToastUtils.showToast(activity, "您已注册成功，请继续完善资料");
                                                           Intent intent = new Intent();
                                                           intent.putExtra("uerId", userId);
                                                           intent.putExtra("userName", ed_register_username.getText().toString());
                                                           intent.putExtra("userPassword", ed_register_password.getText().toString());
                                                           intent.setClass(activity, CompleteInfomation.class);
                                                           startActivity(intent);
                                                           finish();
                                                       } else {
                                                           throw new Exception(msg);
                                                       }
                                                   } catch (Exception e) {
                                                       showErrorDialog( "验证码不正确");
                                                   } finally {
                                                       closeLoadingDialog();
                                                   }
                                               }
                                           }
        );

    }


    /**
     * loginType 0 登录类型
     * account  账号(手机号/qq/微信)
     * password 用户密码
     * deviceId 设备id
     * pushKey 极光推送key
     */
    String password;
    String phone;

    private void userLogin() {
        String type = "0";
        phone = ed_login_username.getText().toString();
        password = ed_login_password.getText().toString();
        String deviceId = SystemUtils.getDeviceKey(activity).trim();
        String pushKey = JPushInterface.getRegistrationID(getApplicationContext());
        HashMap<String, String> parms = new HashMap<String, String>();
        parms.put("loginType", type);
        parms.put("account", phone);
        parms.put("password", password);
        parms.put("deviceId", deviceId);
        parms.put("pushKey", pushKey);
        showLoadingDialog();

        TaskExecutor.getInstance().execute(new PostRequestTask(parms, activity, UrlConsts.USER_LOGIN) {
            @Override
            protected void handleResponse(String response) {
                Log.e("wu", "^^^^^" + response);
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    int infoComplete = object.getInt("infoComplete");
                    closeLoadingDialog();
                    if (code == 0000) {
                        closeLoadingDialog();
                        UserInfo userInfo = new UserInfo();
                        userInfo.parsefromJSON(object.getString("userInfo"));

                        Log.e("wu", String.valueOf(infoComplete));
                        if (infoComplete == 0) {
                            LittleZebraApplication.getInstance().setRegitserUser(userInfo);
                            Intent intent = new Intent();
                            intent.putExtra("uerId", userInfo.userID);
                            intent.putExtra("userName", userInfo.phoneNumber);
                            intent.putExtra("userPassword", userInfo.userPassword);
                            intent.setClass(activity, CompleteInfomation.class);
                            startActivity(intent);
                            finish();
                        } else if (infoComplete == 1) {

                            application.setUserInfo(userInfo);
                            SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_state, true);
                            SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_userCount, phone);
                            SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_password, password);

                            LittleZebraApplication.getInstance().setRegitserUser(userInfo);

                            new Handler() {
                                @Override
                                public void handleMessage(Message msg) {
                                    super.handleMessage(msg);
//                                    if ()
//                                    startActivity(new Intent(activity, HomedActivity.class));
//                                    setResult(RESULT_OK);
////                                    setResult(RESULT_OK, new Intent(activity, HomedActivity.class));
//                                    finish();
//                                    overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
                                    LittleZebraApplication.getInstance().setMainNeedRefresh(true);
                                    back2Main();
                                }
                            }.sendEmptyMessageDelayed(1, 500);
                        }

                    } else {
//                        closeLoadingDialog();
                        throw new Exception(msg);
//                        showErrorDialog(msg);
                    }
                } catch (Exception e) {
                    // ToastUtils.showToast(activity, e.getMessage());
                    showErrorDialog("手机号或密码错误");
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                    closeLoadingDialog();
                }
            }
        });

    }

//    private void showErrorDialog(String message){
//        Bundle bundle = new Bundle();
//        Intent intent =new Intent();
//        intent.setClass(this, ErrorMsgActivity.class);
//        bundle.putString("message",message);
//        intent.putExtras(bundle);
//        startActivity(intent);
//        overridePendingTransition(R.anim.error_msg_in, 0);
//    }

    private void back2Main() {
        startActivity(new Intent(activity, HomedActivity.class));
        finish();
        overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back2Main();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
